/*
 * This file is part of the xOperator SPARQL/XMPP agent.
 * For further information see: http://xoperator.aksw.org
 * Copyright (C) 2007-2008  Jörg Unbehauen

 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.aksw.xoperator.aiml;

import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;

import java.io.IOException;

import org.aksw.xoperator.conf.AgentConfiguration;
import org.aksw.xoperator.sparql.SparqlEndpointFacade;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.XMPPException;

import bitoflife.chatterbean.Match;


/**
 * Listener for the <code><external name="groovy" </code> type of templates.
 *
  */
public class ExternalListenerGroovy extends ExternalListener {
    private Log log = LogFactory.getLog(ExternalListenerGroovy.class);
    private GroovyScriptEngine gse = null;
    private SparqlEndpointFacade sparql;
    private AgentConfiguration aconf;

    public ExternalListenerGroovy(AgentConfiguration aconf,
        SparqlEndpointFacade sparql) {
        super("groovy");
        this.sparql = sparql;
        this.aconf = aconf;

        try {
            gse = new GroovyScriptEngine(aconf.getConfDir() +
                    "/aiml/templates");
        } catch (IOException e) {
            log.error(e);
            throw new RuntimeException(e);
        }
    }

 
    /* (non-Javadoc)
     * @see org.aksw.xoperator.aiml.engine.ExternalListener#perform(bitoflife.chatterbean.Match, java.lang.String)
     */
    @Override
    public String perform(Match match, String param) {
        // finding the path to the aiml files
        ChatContext ccon = (ChatContext) match.getCallback().getContext();
        Binding binding = new Binding();
        binding.setVariable("context", new GroovyContext(match, aconf, sparql));

        try {
            gse.run(param, binding);
        } catch (Exception e) {
        	try {
				ccon.getChat().sendMessage("An execption executing the template was caught: " + e.getCause());
			} catch (XMPPException e1) {
				throw new RuntimeException(e1);
			}
            throw new RuntimeException(e);
        }

        return "";
    }
}
